package com.android.nearshop.io.database;

import java.util.ArrayList;
import java.util.List;

import com.android.nearshop.util.NotifyListener;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-20
 * @see : 搜索关键字缓存
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class SearKeyDB extends DB
{
    private static final String TAG = "SearKeyDB";
    public static final String TABLE_NAME = "searchKey";
    
    public static final String ID = _ID;
    public static final String KEY = "key";  
    public static final String INDEX_SHOPID = "index_shopId";
    public static final String TIME = "time";
    
    //modify by huangyue 离线缓存
    public static final String SQL_CREATE=
        "CREATE TABLE ["+ TABLE_NAME +"] " +
        "(["+ _ID +"] INTEGER NOT NULL PRIMARY KEY autoincrement," +
        "[" + KEY +"] STRING NOT NULL," +
        "[" + INDEX_SHOPID +"] STRING NOT NULL," +
        "[" + TIME + "] TIMESTAMP default (datetime('now', 'localtime')),"+
        "CONSTRAINT MEM_KEY UNIQUE("+KEY+"));";
    //end
    
    private static int BASE_INDEX = 0;
    static final int INDEX_ID = BASE_INDEX;
    private static final int INDEX_KEY = ++BASE_INDEX;
    private static final String UPDATE_INDEXS = "UPDATE %s SET index_shopId = '%s' WHERE key = '%s'";
    private static final String FIND_LIKE_KEY = "SELECT %s FROM %s WHERE key like ?";
    
    /**
     * 更新商户索引到key
     * @param key
     * @return
     */
    public static boolean updateIndexOfShopId(String key, String indexs){
    	SQLiteDatabase db = getDB(true);
        Cursor c = null;
        try
        {
        	db.execSQL(String.format(UPDATE_INDEXS, TABLE_NAME, indexs, key));
        	
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } finally {
        	if(c != null){
        		c.close();
        	}
        }
        
        return false;
    }
    
    /**
     * 模糊搜索key
     * @param key
     * @return
     */
    public static List<String> getLikeKey(String key){
    	List<String> list = new ArrayList<String>();
    	SQLiteDatabase db = getDB(false);
        Cursor c = null;
        
        try
        {
        	c = db.rawQuery(String.format(FIND_LIKE_KEY, KEY, TABLE_NAME), new String[]{"%" + key + "%"});
        	while(c.moveToNext()){
        		String keyword = c.getString(c.getColumnIndex(KEY));
        		if(keyword != null){
        			list.add(keyword);
        		}
        	}
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } finally {
        	if(c != null){
        		c.close();
        	}
        }
        
        return list;
    }
    
    /**
     * 由一个关键字获得相关的shop ids
     * @param key
     * @return
     */
    public static List<Integer> getIndexsByKey(String key){
    	List<Integer> list = new ArrayList<Integer>();
    	
    	 Cursor c = null;
         try
         {
        	SQLiteDatabase db = getDB(true);
         	c = db.query(TABLE_NAME, null, KEY + "=?", new String[]{key}, null, null, null, 8 + "");
         	
         	if(c.moveToNext()){
         		String indexs = c.getString(c.getColumnIndex(INDEX_SHOPID));
         		if(indexs != null && indexs.length() > 0){
         			String[] temps = indexs.split(",");
         			for(int i = 0; i < indexs.length(); i++){
         				list.add(Integer.parseInt(temps[i]));
         			}
         		}
         	}
         
         }
         catch (Exception e)
         {
             e.printStackTrace();
         } finally {
         	if(c != null){
         		c.close();
         	}
         }
    	
    	return list;
    }
    
    /**
     * 保存一个关键字
     * @param key
     * @return
     */
    public static boolean saveKey(String key)
    {
        if(TextUtils.isEmpty(key))
        {
            return false;
        }
        
        SQLiteDatabase db = getDB(true);
        Cursor c = null;
        try
        {
        	c = db.query(TABLE_NAME, null, KEY + "=?", new String[]{key}, null, null, null);
        	
        	if(c.getCount() > 0){
        		return false;
        	}
        	
            ContentValues cv = new ContentValues();           
            cv.put(KEY, key);
            cv.put(INDEX_SHOPID, "");
            
            long id = db.insertOrThrow(TABLE_NAME, null, cv);
            Log.d(TAG, "saveKey = " + key);
            return id > 0;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } finally {
        	if(c != null){
        		c.close();
        	}
        }
        return false;
    }

    /**
     * 获取关键字列表
     * @return
     */
    public static List<String> findList()
    {
        SQLiteDatabase db = getDB(false);       
        Cursor c = null;        
        try
        {
            c = db.query(TABLE_NAME, null, null, null, null, null, null);
            int size = c.getCount();
            if(size == 0) return null;
            List<String> list = new ArrayList<String>(size);
            while(c.moveToNext())
            {
                list.add(c.getString(INDEX_KEY));
            }
            return list;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != c)
            {
                c.close();
            }
        }
        return null;
    }
    
    /**
     * 清除指定天数之前的缓存
     * @param day
     * @return
     */
    public static boolean clearPreNDay(int day)
    {
        String section = null;
        if(day > 0)
        {
            section =  TIME + " < datetime('now','-"+day+" day')";
        }
        return clear(TABLE_NAME, section);
    }
    
    public static void clearPreNDayAsyn(final int day,final NotifyListener<Boolean> listener)
    {
        new AsyncTask<Void, Void, Boolean>()
        {
            @Override
            protected Boolean doInBackground(Void... params)
            {
                return clearPreNDay(day);
            }
            
            protected void onPostExecute(Boolean result) 
            {
                if(listener != null)
                {
                    listener.onSucceed(result);
                }
            };
        }.execute();
    }
    
    public static void test()
    {
        saveKey("zhao");
    }
}
